package webServer

import (
	"fmt"
	"go-way/handler"
	"log"
	"net/http"
	"sync"
)

var mu sync.Mutex

// 统计某个url被访问的次数
var count int

func handler(w http.ResponseWriter, r *http.Request) {

	// 获取请求的相关信息
	fmt.Fprintf(w, "%s %s %s \n", r.Method, r.URL, r.Proto)

	// 获取请求的header
	for k, v := range r.Header {
		fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
	}

	// 请求参数
	if err := r.ParseForm(); err != nil {
		// err 变量被限制在这个判断中
		log.Print(err)
	}

	for k, v := range r.Form {
		fmt.Fprintf(w, "Form[%q] = %q\n", k, v)
	}

	mu.Lock()
	count++
	mu.Unlock()
	fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
}

func countHandler(w http.ResponseWriter, r *http.Request) {
	mu.Lock()
	count++
	mu.Unlock()
	fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
}

func gifHandler(w http.ResponseWriter, r *http.Request) {
	// 同样都是标准输出流
	generatePicture.GenImage(w)
}

func GenServer() {
	http.HandleFunc("/", handler)
	http.HandleFunc("/count", countHandler)
	http.HandleFunc("/gif", gifHandler)
	log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
